import requests
from lxml import etree

from day05.captcha_tool import solve_captcha


def get_session():
    session = requests.Session()
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36',
    }
    session.headers.update(headers)
    return session


def get_login_page(session, url):
    res = session.get(url)
    res.raise_for_status()
    return res.text


def parse_login_page(html):
    tree = etree.HTML(html)
    img_url = tree.xpath('//img[@id="imgCode"]/@src')[0]
    full_img_url = "https://so.gushiwen.cn" + img_url
    __VIEWSTATE = tree.xpath('//input[@id="__VIEWSTATE"]/@value')[0]
    return full_img_url, __VIEWSTATE


def download_captcha_image(session, url, filename):
    res = session.get(url)
    res.raise_for_status()
    with open(filename, "wb") as f:
        f.write(res.content)


def login(session, login_url, viewstate, captcha_code):
    data = {
        "__VIEWSTATE": viewstate,
        "__VIEWSTATEGENERATOR": "C93BE1AE",
        "from": "http://so.gushiwen.cn/user/collect.aspx",
        "email": "13503450662",
        "pwd": "test123456",
        "code": captcha_code,
        "denglu": "登录"
    }
    response = session.post(login_url, data=data)
    response.raise_for_status()
    return response.text


def save_page(html, filename):
    with open(filename, "w", encoding="utf-8") as f:
        f.write(html)


def main():
    session = get_session()
    login_page = get_login_page(session,
                                "https://so.gushiwen.cn/user/login.aspx?from=http://so.gushiwen.cn/user/collect.aspx")
    img_url, viewstate = parse_login_page(login_page)
    download_captcha_image(session, img_url, "RandCode.png")
    captcha_code = solve_captcha(uname="13503450662", pwd="test123456", img_path='./RandCode.png', typeid=3)
    response_text = login(session,
                          "https://so.gushiwen.cn/user/login.aspx?from=http%3a%2f%2fso.gushiwen.cn%2fuser%2fcollect.aspx",
                          viewstate, captcha_code)
    if "退出登录" in response_text:
        print("登录成功")
        save_page(response_text, "page.html")
        print("页面已保存为 page.html")
    else:
        print("登录失败")


if __name__ == "__main__":
    main()
